﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MethodWorx.CMS.Content;
using System.Web.Mvc;
using MethodWorx.CMS.UI.Models.Shared;
using MethodWorx.CMS.Requests;
using MethodWorx.CMS.Services;
using MethodWorx.Core.DomainModel;
using MethodWorx.Core.Validation;
using MethodWorx.CMS.Membership;

namespace MethodWorx.CMS.UI.Areas.Application.Models
{
    public class CreatePageModel
    {
        public CreatePageRequest Request { get; set; }

        private SchemaService schema;
        private ContentService content;
        private User user;

        public CreatePageModel(SchemaService schema, ContentService content, User user)
        {
            this.content = content;
            this.schema = schema;
            this.user = user;
        }

        public void Initialize(Guid? id)
        {
            if (id.HasValue)
            {
                var page = this.content.GetPageById(id.Value);
                if (page == null)
                    throw new BusinessRuleException("Page Not Found");

                this.Request = new CreatePageRequest(page, this.user);
            }
            else
                this.Request = new CreatePageRequest(this.user);
        }

        public SelectList GetPageTemplateSelectList()
        {
            return new SelectList(schema.GetAllPageTemplates().Where(pt => pt.Abstract == false), "Id", "Name");
        }

        public SelectList GetParentTemplateSelectList()
        {
            return new SelectList(schema.GetAbstractPageTemplates(), "Id", "Name");
        }

        public PageTemplateConstraint GetConstraint(PageTemplate child)
        {
            if (this.Request.ParentPage != null)
            {
                foreach(var constraint in this.Request.ParentPage.Template.PageTemplateConstraints)
                {
                    if (constraint.RelatedTemplate == child)
                        return constraint;
                }
            }
            
            return null;
        }

        public void Complete(IValidationProvider validation)
        {
            this.content.CreatePage(this.Request, validation);
        }

        internal void ValidatePublishedPageTemplates(CreatePageRequest createPageRequest, IValidationProvider validation)
        {
            this.content.ValidatePublishedPageTemplates(createPageRequest, validation);
        }
    }
}
